<template>
  <div
    id="center"
    ref="fullscreenContainer"
    :class="{ fullscreen: isFullscreen }"
  >
    <div class="bg-color-black">
      <div class="controls">
        <button @click="back" class="close-back">返回</button>
        <button @click="toggleFullScreen" class="fullscreen-btn">
          {{ isFullscreen? "⨉" : "⛶" }}
        </button>
      </div>
      <div id="mapChart"></div>
      <div v-if="isLoading" class="loading-overlay">
        <div class="spinner"></div>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from "echarts";
import screenfull from "screenfull";
import nameMap from '../assets/json/nameMap.json';
import provinces from '../assets/json/provinces.json';
import provincesText from '../assets/json/provincesText.json';
import {mapActions} from "vuex";
import * as XLSX from 'xlsx';
import xlsxFile from '../assets/data/data.xlsx'; // 通过 webpack 引入


const borderColor = "#e6e8ed";
const chinaColor = "#7fa0dd";
const worldColor = "#58a8d2";
const hoverColor = "rgba(109, 116, 172)";
const textColor = "#243a4e";


export default {
  name: "CenterWithMap",
  data() {
    return {
      isFullscreen: false,
      isLoading: false,
      myChart: null,
      articleData: [],
      userData: {
        id: null,
        username: null,
        email: null,
        role: null
      }
    };
  },
  mounted() {
    this.userData.id = this.$store.state.user.userInfo.id;
    // this.userData.username = this.$store.state.user.userInfo.username;
    // this.userData.email = this.$store.state.user.userInfo.email;
    // this.userData.role = this.$store.state.user.userInfo.role;
    this.initMap();
    window.addEventListener("resize", this.handleResize);
    if (screenfull.isEnabled) {
      screenfull.on("change", this.updateFullscreenState);
    }
    setTimeout(() => {
      const rect = document.getElementById("mapChart").getBoundingClientRect();
      console.log("初始 mapChart 尺寸", rect);
    }, 500);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.handleResize);
    if (screenfull.isEnabled) {
      screenfull.off("change", this.updateFullscreenState);
    }
  },
  methods: {
    ...mapActions(['companyDistribution']),
    toggleFullScreen() {
      if (screenfull.isEnabled) {
        this.isLoading = true;
        screenfull.toggle(this.$refs.fullscreenContainer);
        setTimeout(() => {
          this.isLoading = false;
          requestAnimationFrame(() => {
            this.handleResize();
          });
        }, 1000);
      }
    },
    updateFullscreenState() {
      this.isFullscreen = screenfull.isFullscreen;
      this.isLoading = true;
      setTimeout(() => {
        this.isLoading = false;
        requestAnimationFrame(() => {
          this.handleResize();
        });
      }, 1000);
    },
    back() {
      this.initMap();
      const backBtn = document.querySelector(".close-back");
      if (backBtn) backBtn.style.display = "none";
    },
    async initMap() {
      const chartDom = document.getElementById("mapChart");
      if (!chartDom) return;

      this.myChart = echarts.init(chartDom);
      const backBtn = document.querySelector(".close-back");
      if (backBtn) backBtn.style.display = "none";

      try {
        const response = await fetch(xlsxFile);
        if (!response.ok) {
          throw new Error(`HTTP error! status: ${response.status}`);
        }

        const arrayBuffer = await response.arrayBuffer();
        const workbook = XLSX.read(arrayBuffer, {type: 'array'});

        const sheetName = '全球文章分布';
        const worksheet = workbook.Sheets[sheetName];
        if (!worksheet) {
          throw new Error('找不到工作表: 全球文章分布');
        }

        const data = XLSX.utils.sheet_to_json(worksheet, {header: 1});

        // 假设第一行是表头，从第二行开始加载数据
        for (let i = 1; i < data.length; i++) {
          this.articleData.push({
            name: data[i][0],
            articleCount: data[i][1]
          });
        }
      } catch (error) {
        console.error('读取文件时出错:', error);
}

const articleData = this.articleData;

const drawMap = (name) => {
  const mapJson = name === "world"
    ? require("@/assets/json/world.json")
    : require("@/assets/json/province/" + name + ".json");

  if (!mapJson) {
    console.error("无法加载地图数据:", name);
    return;
  }

  echarts.registerMap(name, mapJson);
  const newCenter = name === "world"? [80.0, 35.0] : mapJson.center;
  const newZoom = name === "world"? 3 : 1;

  const option = {
    tooltip: {
      show: true,
      trigger: "item",
      formatter: (params) => {
        const articleItem = articleData.find(d => d.name === params.name);
        return articleItem
          ? `${params.name}<br>文章数量: ${articleItem.articleCount}`
          : params.name;
      }

    },
    visualMap: {
      show: true,
      min: 0,
      max: Math.max(...articleData.map(d => d.articleCount)) || 100,
      left: "left",
      bottom: "10%",
      text: ["高数量", "低数量"],
      textStyle: { color: "white" },
      calculable: true,
      realtime: true,
      inRange: {
        color: ["#c9e2cb", "#98c89e", "#6aa875", "#2e8b57"],
      }
    }

    ,
    geo: {
      show: true,
      map: name,
      zoom: newZoom,
      center: newCenter,
      roam: true,
      label: {
        show: newZoom > 3,
        color: textColor,
        fontSize: 12,
      },
      itemStyle: {
        normal: {
          borderColor,
          areaColor: name === "world"? worldColor : chinaColor,
        },
        emphasis: { areaColor: hoverColor },
      },
      nameMap,
    },
    series: [
      {
        type: "map",
        map: name,
        geoIndex: 0,
        selectedMode: false,
        // 使用 articleValue 作为可视化数值
        data: articleData.map(d => ({ name: d.name, value: d.articleCount }))
      },
    ],
  };

  this.myChart.setOption(option);
  this.myChart.on("georoam", () => {
    const zoomLevel = this.myChart.getOption().geo[0].zoom;
    this.myChart.setOption({
      geo: { label: { show: zoomLevel > 3 } }
    });
  });
};

// 初始显示世界地图
let selected = "world";
drawMap(selected);

// 点击地图切换省级区域
this.myChart.on("click", (param) => {
  const backBtn = document.querySelector(".close-back");
  for (let i = 0; i < provincesText.length; i++) {
    if (param.name.includes(provincesText[i])) {
      if (backBtn) backBtn.style.display = "block";
      drawMap(provinces[i]);
      break;
    }
  }
});
},
handleResize() {
  if (this.myChart) {
    this.myChart.resize();
  }
}
}
};
</script>

<style lang="scss" scoped>
/* 样式保持不变 */
#center {
  position: relative;
  width: 800px;
  height: 620px;
  margin: 0 auto;
  transition: all 0.3s ease;
}

.fullscreen {
  width: 100vw!important;
  height: 100vh!important;
  margin: 0;
}

.bg-color-black {
  width: 100%;
  height: 100%;
  padding: 5px;
  border-radius: 10px;
  box-sizing: border-box;
  position: relative;
}

.controls {
  position: absolute;
  top: 10px;
  right: 10px;
  z-index: 10;
  display: flex;
  gap: 10px;
}

.close-back,
.fullscreen-btn {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid #ccc;
  padding: 5px 10px;
  cursor: pointer;
  border-radius: 4px;
  font-size: 16px;
}

#mapChart {
  width: 100%;
  height: 100%;
  border-radius: 10px;
  transition: width 0.3s ease, height 0.3s ease;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: #0C0F32;
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.spinner {
  border: 6px solid #f3f3f3;
  border-top: 6px solid #3498db;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style>
